package ynu.edu.controller;

import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import ynu.edu.common.Result;
import ynu.edu.entity.FoodCategory;
import ynu.edu.service.FoodCategoryService;

import java.util.List;

/**
 * 食品分类控制器
 */
@RestController
@RequestMapping("/categories")
public class FoodCategoryController {
    
    @Autowired
    private FoodCategoryService foodCategoryService;
    
    /**
     * 根据分类ID获取分类详情
     *
     * @param categoryId 分类ID
     * @return 分类详情
     */
    @GetMapping("/{categoryId}")
    @CircuitBreaker(name = "foodServiceBreaker", fallbackMethod = "getCategoryByIdFallback")
    public Result<FoodCategory> getCategoryById(@PathVariable Integer categoryId) {
        FoodCategory category = foodCategoryService.getCategoryById(categoryId);
        return Result.success(category);
    }
    
    /**
     * 根据商家ID获取分类列表
     *
     * @param businessId 商家ID
     * @return 分类列表
     */
    @GetMapping("/business/{businessId}")
    @CircuitBreaker(name = "foodServiceBreaker", fallbackMethod = "getCategoriesByBusinessIdFallback")
    public Result<List<FoodCategory>> getCategoriesByBusinessId(@PathVariable Integer businessId) {
        List<FoodCategory> categories = foodCategoryService.getCategoriesByBusinessId(businessId);
        return Result.success(categories);
    }
    
    /**
     * 根据商家ID和分类ID获取分类详情
     *
     * @param businessId 商家ID
     * @param categoryId 分类ID
     * @return 分类详情
     */
    @GetMapping("/business/{businessId}/category/{categoryId}")
    @CircuitBreaker(name = "foodServiceBreaker", fallbackMethod = "getCategoryByBusinessIdAndCategoryIdFallback")
    public Result<FoodCategory> getCategoryByBusinessIdAndCategoryId(@PathVariable Integer businessId, @PathVariable Integer categoryId) {
        FoodCategory category = foodCategoryService.getCategoryByBusinessIdAndCategoryId(businessId, categoryId);
        return Result.success(category);
    }
    
    // 熔断降级方法
    public Result<FoodCategory> getCategoryByIdFallback(Integer categoryId, Exception e) {
        return Result.failed("获取分类详情失败，请稍后再试: " + e.getMessage());
    }
    
    public Result<List<FoodCategory>> getCategoriesByBusinessIdFallback(Integer businessId, Exception e) {
        return Result.failed("获取商家分类列表失败，请稍后再试: " + e.getMessage());
    }
    
    public Result<FoodCategory> getCategoryByBusinessIdAndCategoryIdFallback(Integer businessId, Integer categoryId, Exception e) {
        return Result.failed("获取分类详情失败，请稍后再试: " + e.getMessage());
    }
} 